package com.code2roc.jarmanage.firewall;

import com.code2roc.jarmanage.util.CMDUtil;
import com.code2roc.jarmanage.util.FileUtil;

import java.io.File;
import java.text.MessageFormat;

public class LinuxUFWService implements FireWallService {
    @Override
    public boolean addRule(String name, String protocol, String port, String action) {
        protocol = protocol.toLowerCase();
        String command = MessageFormat.format("ufw allow {0}{1}{2}", port, "/", protocol);
        CMDUtil.executeLinuxCommand(command);
        command = "ufw reload";
        CMDUtil.executeLinuxCommand(command);
        command = "ufw status";
        String filePath = CMDUtil.executeLinuxCommandWithStore(command);
        String result = FileUtil.readFileContent(filePath);
        if (result.indexOf(port + "/" + protocol)>=0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean deleteRule(String name, String protocol, String port, String action) {
        protocol = protocol.toLowerCase();
        String command = MessageFormat.format("ufw delete allow {0}{1}{2}", port, "/", protocol);
        CMDUtil.executeLinuxCommand(command);
        command = "ufw reload";
        CMDUtil.executeLinuxCommand(command);
        command = "ufw status";
        String filePath = CMDUtil.executeLinuxCommandWithStore(command);
        String result = FileUtil.readFileContent(filePath);
        if (result.indexOf(port + "/" + protocol)<0) {
            return true;
        } else {
            return false;
        }
    }
}
